local util  = require("shared.api.util")


local _M = {}

do
  local _M_mt = { __index = _M }


  local function _get_stream_key(workspace, stream)
    return "stream:"..workspace.."/"..stream
  end


  function _M.new(redis, workspace, db)
    assert(redis)
    assert(workspace)

    return setmetatable({
      redis       = redis,
      workspace   = workspace,
      db          = db  or 0,
    }, _M_mt)
  end


  function _M.write(self, stream, message)
    assert(self)
    assert(self.redis)
    assert(self.workspace)
    assert(type(stream)=="string")
    assert(type(message)=="table")

    local redis      = self.redis
    local stream_key = _get_stream_key(self.workspace, stream)
    local stream_db  = self.db  or  0

    if next(message) then
      local _, err = redis:SELECT(stream_db)
      if err then
        return nil, err
      end
      local res, err = redis:XADD(stream_key, '*',
                                unpack(
                                  util.normalize_field_value_args(message)
                                ))
      if err then
        return nil, err
      end
      return res
    end
  end
end
return _M
